import hashlib
import os
hash_file_path=(f"file_hash")
chunk_cnt=0
new_hash_list=list()
file1_path=input("请输入文件1的路径")
file2_path=input("请输入文件2的路径")
chunk_size=int(input("请输入分块长度"))


def cal_hash(file_content):
    # 确保输入是字节类型
    if not isinstance(file_content, bytes):
        raise TypeError("输入必须是字节类型")

    # 创建 SHA-256 对象
    sha256_hash = hashlib.sha256()

    # 用数据更新哈希对象
    sha256_hash.update(file_content)

    # 计算并返回哈希值
    return sha256_hash.hexdigest()


def chunk(filepath ,chunk_size,old_hash_list):

    with open(filepath,'rb') as in_file:
        global chunk_cnt
        global new_hash_list
        while True:
            chunk=in_file.read(chunk_size)
            chunk_value=str(cal_hash(chunk))
            ##print (f"chunk_calue{chunk_cnt }:{chunk_value }")
            if not chunk :
                break
            elif chunk_value  in old_hash_list or chunk_value ==None :
                continue
            else :
                out_file_path=f'chunk_{chunk_cnt }.bin'
                with open (out_file_path ,'wb') as out_file:
                    out_file .write(chunk)
                    chunk_cnt +=1
                    new_hash_list.append(chunk_value )

def chunking_files (file1_path ,file2_path ,chunk_size,old_hash_list ):
    chunk(file1_path, chunk_size,old_hash_list )
    chunk(file2_path, chunk_size,old_hash_list )
def get_file_hash_value(hash_file_path):
    if not os.path.exists(hash_file_path):
        with open(hash_file_path, 'w') as f:
            pass

    hash_list=list()
    with open(hash_file_path ) as f:
        for line in f:
            hash_list .append(line.strip())
    return hash_list


def set_file_hash_value(new_hash_list):
    with open(hash_file_path,'a' )as f:
         for _ in new_hash_list :
             f.write(_+'\n')






def main():
    old_hash_list=get_file_hash_value(hash_file_path )
    chunking_files(file1_path, file2_path, chunk_size,old_hash_list )
    set_file_hash_value(new_hash_list )


if __name__ == "__main__":
    main()





